package com.topway.dsmflex.thread.services;

import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.topway.dsmflex.dao.BaseDao;
import com.topway.dsmflex.model.synchro.DataSourceBean;
import com.topway.dsmflex.model.synchro.DataTableBean;
import com.topway.dsmflex.thread.handler.DataHandle;
import com.topway.dsmflex.util.JdbcHelp;




/**
 * 
 * @author liusy 2013-05-2
 *
 */
public abstract class AbstractSynchroServices extends BaseDao implements ISynchroServices{
	protected static Logger log = Logger.getLogger(AbstractSynchroServices.class);
	

	protected DataSourceBean dsTarget = null; 
	protected DataSourceBean dsSource = null;
	
	protected Connection connTarget = null;
	protected Connection connSource = null;
	
	
	protected void isDataSources(DataSourceBean  _dsSource,DataSourceBean  _dsTarget) throws SQLException
	{
		if(null!=_dsSource)
		{
			if(null==dsSource || !dsSource.getDataSourceName().equals(_dsSource.getDataSourceName())||connSource.isClosed())
			{
				try {
					dsSource = _dsSource;
					connSource = JdbcHelp.getConnection(dsSource);
				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}
		if(null!=_dsTarget)
		{
			if(null==dsTarget || !dsTarget.getDataSourceName().equals(_dsTarget.getDataSourceName())||connTarget.isClosed())
			{
				try {
					dsTarget = _dsTarget;
					connTarget = JdbcHelp.getConnection(dsTarget);
				} catch (Exception e) {
					log.error(e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}
	

	protected DataHandle dataHandle = null;
	
	  public int synchroInsertData(Connection SourceConn,Connection targetConn,DataTableBean dt) throws SQLException {
		  return synchroData(SourceConn,targetConn,dt);	
	  }
	  
	  public int synchroInsertOrUpdateData(Connection SourceConn,Connection targetConn,DataTableBean dt) throws SQLException {
		  return synchroData(SourceConn,targetConn,dt);
	  }
	  
	  public int synchroUpdateData(Connection SourceConn,Connection targetConn,DataTableBean dt) throws SQLException {
		  return synchroData(SourceConn,targetConn,dt);
	  }
	  
	  public int synchroDeleteData(Connection SourceConn,Connection targetConn,DataTableBean dt) throws SQLException {
		  return synchroData(SourceConn,targetConn,dt);
	  }
	  
 
	  protected Map<String,Object> lobMap = new HashMap<String,Object>();
	  protected List<Map<String,String>> listMap = new ArrayList<Map<String,String>>();
	  
		 public abstract int synchroData(Connection sourceConn, Connection targetConn, DataTableBean dt) throws SQLException;
		 
	  
	  
	public int updateTableState(Connection conn, String sql) throws SQLException {
			int result = 0;
			Statement stmt = null;
			try {
				stmt = conn.createStatement();
				result=	stmt.executeUpdate(sql);
				conn.commit();
			} catch (Exception e) {
				log.error(e.getMessage());
				e.printStackTrace();
			}finally{
				if(null!=stmt)
					stmt.close();
			}
			return result;
		}

	  
	  public List<Map<String,String>> getListMap(ResultSet rs, Map<String,Integer> mapColumnType)
	  {
		  Map<String,String> map = null;
			  try {
			      while (rs.next()) {
			    	  map = new HashMap<String, String>();
			  	 	for (Entry<String, Integer> mapColumnTypeEntry : mapColumnType.entrySet()) {
			  	 		getResultMap(map, rs, mapColumnTypeEntry.getValue(),mapColumnTypeEntry.getKey());
	    		 	}
			         listMap.add(map);
			      }
			} catch (Exception e) {
				e.printStackTrace();
			}

		  return listMap;
	  }
	  
	  
	  public int execClearBatch(PreparedStatement ps ) throws SQLException
	  {	
			 int  [] reuslt = ps.executeBatch();
        	 ps.clearBatch();
        	 return reuslt.length;
	  }
	  
	  

	  
	  private Map<String,String> getResultMap(Map<String,String> map ,ResultSet rs,int typeName,String  columnName) throws SQLException
	  {
			map.put(columnName, getResultStr(rs,typeName, columnName));
		return map;
	  }  

	  
	  
	  
	  	private Timestamp timestamp_= null;
	  	private Long long_= null;
	  	private int int_= 0;
	  	private Object object_ = null;
	  	private Blob blob_ =null;
	  	private Clob clob_=null;
	  	private double double_  = 0;
	  	private String key_ = "";
	  	private String value_ = "";
			  
	  	protected String getResultStr(ResultSet rs,int typeName,String  columnName) throws SQLException
			  {
		           if (typeName == Types.DATE) {
		        	   timestamp_ = rs.getTimestamp(columnName);
		               if (rs.wasNull())
		                 return "null";
		               else {
		                  return formatDate.format(timestamp_.getTime());
		               }
		            } else if (typeName == Types.TIMESTAMP) {
		            	   timestamp_ = rs.getTimestamp(columnName);
		               if (rs.wasNull())
		                  return "null";
		               else {
		                  return formatStamp.format(timestamp_.getTime());
		               }
		            } else if (typeName == Types.TIME) {
		            	   timestamp_ = rs.getTimestamp(columnName);
		               if (rs.wasNull())
		                 return "null";
		               else {
		                  return formatDate.format(timestamp_.getTime());
		               }
		            } else if (typeName == Types.INTEGER) {
		               int_ = rs.getInt(columnName);
		               if (rs.wasNull())
		               return "null";
		               else {
		            	   return String.valueOf(int_);
		               }
		            } else if (typeName == Types.BIGINT) {
		               long_ = rs.getLong(columnName);
		               if (rs.wasNull())
		                 return "null";
		               else {
		                  return String.valueOf(long_);
		               }
		            } else if (typeName == Types.BLOB) {
			               blob_ = rs.getBlob(columnName);
			               String key = "";
			               if (rs.wasNull())
			                 return "null";
			               else {
			            	   key =java.util.UUID.randomUUID().toString();
			            	   lobMap.put(key,blob_);
			                  return key;
			               }
			            }
		            else if (typeName == Types.CLOB) {
		            		clob_ = rs.getClob(columnName);
			             
			               if (rs.wasNull())
			                 return "null";
			               else {
			            	   key_ =java.util.UUID.randomUUID().toString();
			            	   lobMap.put(key_,clob_);
			                  return key_;
			               }
			            }else if (typeName == Types.DECIMAL || typeName == Types.NUMERIC || typeName == Types.FLOAT) {
			            	double_ = rs.getDouble(columnName);
			            	value_="";
		               if (rs.wasNull())
		                 return "null";
		               else {
		            	   value_ = String.valueOf(double_);
								if(value_.indexOf(".")==value_.length()-2&&value_.lastIndexOf("0")==value_.length()-1)
									value_ = value_.substring(0, value_.indexOf("."));
		               }
		               return value_;
		            } else {
		            	object_=rs.getObject(columnName);
		               if (rs.wasNull())
		                return "null";
		               else {
		                return object_.toString();
		               }
		            }
			  }  
			  
			  public static void main(String[] args) 
			  {
				  DataTableBean  aa = new DataTableBean("11");
		
				     Map<String,Object> mapColExpress = new HashMap<String,Object>();
				     mapColExpress.put("1",aa);
					  aa = new DataTableBean("22");
//				     mapColExpress.put("2", "a");
//				     mapColExpress.put("3", "a");
//				     mapColExpress.put("4", "a");
//				     mapColExpress.put("5", "a");
//				     mapColExpress.put("6", "a");
//				     mapColExpress.put("7", "a");
//				     mapColExpress.put("8", "a");
//				     mapColExpress.put("9", "a");
//				     mapColExpress.put("10", "a");
				     
//					    for (int i = 0; i < 10; i++) {
//					    	for (Entry<String, String> entry : mapColExpress.entrySet()) {
//						 		entry.setValue(entry.getValue()+i);
//					    	}		
//						}
//					     
//					    for (Entry<String, String> entry : mapColExpress.entrySet()) {
//					 		System.out.println(entry.getValue());
//				    	}	
				   
				     aa = (DataTableBean) mapColExpress.get("1");
				     	System.out.println(aa.getTableNameSource());
						  System.out.println(((DataTableBean)mapColExpress.get("1")).getTableNameSource());
					    	System.out.println(aa.getTableNameSource());
							  System.out.println(((DataTableBean)mapColExpress.get("1")).getTableNameSource());
						 
							  
							  
							  DataTableBean  bb = new DataTableBean("11");
								
							     List<DataTableBean> list = new ArrayList<DataTableBean>();
							     list.add(bb);
								  bb = new DataTableBean("22");

							   
							     //bb = list.get(0);
							     //bb.setTableNameSource("22");
							    System.out.println(bb.getTableNameSource());
									  System.out.println(list.get(0).getTableNameSource());
								 System.out.println(bb.getTableNameSource());
										  System.out.println(list.get(0).getTableNameSource());
									  
			}

}
